<?php

/**
 * 用户管理
 * @author hfc
 * time 2015-7-5
 */

namespace apps\admin\controllers;
if( !defined( 'APP_ROOT' ) ){ echo 'Direct Access Deny!'; return; }

use apps\admin\models\PriUsers;
use enums\DBEnums;
use enums\PriEnums;
use helpers\TimeUtils;
use Phalcon\Paginator\Adapter\QueryBuilder;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
use apps\admin\models\PriRoles;
use enums\PromoterTypeEnums;
use apps\admin\bizs\MessagesBiz;
use apps\admin\enums\DisplayEnums;
use apps\admin\ext\AdminBaseController;

class UsersController extends AdminBaseController
{
    public function initialize()
    {
        parent::initialize();
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '管理员的首页' )	
     * @method( method = 'indexAction' )
     * @op( op = 'r' )		
    */
    public function indexAction()
    {
        $iPage = $this->request->getQuery( 'page', 'int' );
        $iCurrPage = $iPage ? $iPage : 1;

        $where = 'u.delsign=' . DBEnums::DELSIGN_NO;

        $builder = $this->modelsManager->createBuilder()
        	->columns( 'u.id,u.loginname,u.nickname,u.name,u.email,r.name as roleName,u.status,
        			 u.role_id' )
			->addFrom( 'apps\admin\models\PriUsers', 'u' )
        	->join( 'apps\admin\models\PriRoles', 'r.id=u.role_id', 'r' )
        	->where( $where );
        
        $paginator = new QueryBuilder(
    		array(
        	   'builder' => $builder,
    		   'limit' => DisplayEnums::PER_PAGE_LIST_NUM,
    		   'page' => $iCurrPage
        ) );
        
        $page = $paginator->getPaginate();
        $this->view->page = $page;
        $this->view->forbidId = [ PriEnums::SUPER_ADMIN_ID, $this->userInfo[ 'id' ] ];
        $this->view->myId = $this->userInfo[ 'id' ];
    }
    
    
    /**
     * @author( author='New' )
     * @date( date = '2016-8-19' )
     * @comment( comment = '保存单条站内信（新信件或草稿）' )
     * @method( method = 'sendMessage' )
     * @op( op = 'w' )
     */
    public function saveMessageAction()
    {
    	if( $this->request->getPost() )
    	{
    		$senderType = PromoterTypeEnums::PROMOTER_PLATFORM;
    		$senderId = $this->userInfo[ 'id' ];
    		$receiverType = PromoterTypeEnums::PROMOTER_COMMOM;
    		$receiverId = $this->request->getPost( 'receiver_id', 'int' );
    		$msgStatus = $this->request->getPost( 'status', 'int' );
    		$content = $this->request->getPost( 'content', 'string' );
    		$title = $this->request->getPost( 'title', 'string' );
    
    		$biz = new MessagesBiz();
    		$res = $biz->sendMessage( $senderType, $senderId, $receiverType, $receiverId, $msgStatus, $content, $title );
    
    		if( $res )
    		{
    			$ret[ 'state' ] = 0;//操作成功
    		}
    		else
    		{
    			$ret[ 'state' ] = 2;//操作失败
    		}
    	}
    	else
    	{
    		$ret[ 'state' ] = 1;//参数错误
    	}
    	echo json_encode( $ret );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '编辑用户界面显示' )	
     * @method( method = 'editAction' )
     * @op( op = '' )		
    */
    public function editAction( $isAdd )
    {
        $id = $this->request->getQuery( 'id', 'int' );
        $this->checkSelf( $id ); //判断一下是否是自己
        if( $id )
        {
        	$user = PriUsers::findFirst( array( 'id=?0', 'bind' => array( $id ), 'columns' => "id,name,nickname,loginname,email,role_id" ) );
        	if( $user )
        	{
        		$this->view->user = $user->toArray();
        	}
        }
        
        if( $this->userInfo[ 'id' ] != $id ) //编辑其他人的, 自己不可编辑自己的角色
        {
	        $objRoles = new PriRoles();
        	$this->view->roles = $objRoles->getRoles();
        }
    }
    
    
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '添加用户界面显示' )	
     * @method( method = 'addAction' )
     * @op( op = '' )		
    */
    public function addAction()
    {
    	$objRoles = new PriRoles();
    	$this->view->roles = $objRoles->getRoles();
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax 请求 更新用户' )	
     * @method( method = 'updateAction' )
     * @op( op = 'u' )		
    */
    public function updateAction()
    {
       	if( ! $this->csrfCheck() ){ return false; }
        
        $userId = $this->request->getPost( 'userId', 'int' );
        $this->checkSelf( $userId );
        
        $data[ 'id' ] = $userId;
        $set = '';
        
        $roleId = $this->request->getPost( 'roleId', 'int' );
        if(  $roleId ) //获得到分组
        {
            $set = ',role_id=:role_id:';
            $data[ 'role_id' ] =  $roleId;  
        }    
        
        $data[ 'email' ] = $this->request->getPost( 'email', 'email' );
        $data[ 'name' ] = $this->request->getPost( 'name', 'trim' );
        $data[ 'nickname' ] = $this->request->getPost( 'nickname', 'trim' );
        $this->validation( $data );//验证数据
        
        $phql = 'UPDATE apps\admin\models\PriUsers SET name=:name:, email=:email:, nickname=:nickname: ' . $set . ' WHERE id=:id:';
        $status = $this->modelsManager->executeQuery( $phql, $data );
        
        if( $status->success() )
            return $this->success( '更新成功' );
        else
            return $this->error( '更新失败' );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax请求 修改密码' )	
     * @method( method = 'changePassword' )
     * @op( op = 'u' )		
    */
    public function changePasswordAction()
    {
        if( ! $this->csrfCheck() )
        { 
            return false; 
        }
        
        $userId = $this->request->getPost( 'userId', 'int' );
        if( ! $this->checkSelf( $userId ) )
        {
            return false;
        }
        
        $oldPassword = $this->request->getPost( 'oldPassword', 'trim' );
        if( $oldPassword )
        {
            $user = PriUsers::findFirst( array( 'id=?0','bind' => array( $userId ))  );
            if( $user )
            {
                $pwd = sha1( $this->session->getId() . $user->pwd );
                if( $pwd != $oldPassword )
                {
                    $ret[ 'state' ] = 1;//原密码不正确
                    return $this->error( '', [ 'state' => 1 ]);
                }
            }
        }
        else
        {
            $ret[ 'state' ] = 2;//请输入原密码
            return $this->error( '', [ 'state' => 2 ]);
        }
        
        $password = $this->request->getPost( 'password', 'trim' );
        $repassword = $this->request->getPost( 'repassword', 'trim' );
        if( $password != $repassword )
        {
            $ret[ 'state' ] = 3;//两次输入密码不一致
            return $this->error( '', [ 'state' => 3 ]);
        }
        
        if( $user )
        {
            if( $user->update( array( 'pwd' => $password ) ) )
            {
                $ret[ 'state' ] = 0;//密码修改成功
                return $this->success( '', [ 'state' => 0 ]);
            }
            else
           {
                $ret[ 'state' ] = 4;//密码修改失败
                return $this->error( '', [ 'state' => 4 ]);
            }
        }
        else
        {
        	return $this->error( '用户不存在', [ 'state' => 5 ]);
        }
       
    }

    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax 请求 删除用户' )	
     * @method( method = 'deleteAction' )
     * @op( op = 'd' )		
    */
    public function deleteAction()
    {
       	if( ! $this->csrfCheck() ){ return false; }
       	
        $id = $this->request->getPost( 'id', 'int' );
        $user =  PriUsers::findFirst( array( 'id=?0', 'bind' => array( $id )) );
        if( $user )
        {
            $status = $user->update( array( 'delsign' => DBEnums::DELSIGN_YES, 'uptime' => date( 'Y-m-d H:i:s')));
            if( $status )
                 return $this->success( '删除成功' );
        }
        return $this->error( '删除失败' );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2016-6-27' )
     * @comment( comment = 'ajax 请求 检验登录名' )	
     * @method( method = 'checkLoginNameAction' )
     * @op( op = 'r' )		
    */
    public function checkLoginNameAction()
    {
        $loginname = $this->request->get( 'loginname', 'string' );
        $where = array( 'loginname = :name:', 'bind' => array( 'name' => $loginname ) );
        $priUser = PriUsers::findFirst( $where );
        
        if( ! $priUser )
            return $this->success( '账号不存在' );
        else
            return $this->error( '账号已经存在' );
    }

    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax 请求 添加一个新用户' )	
     * @method( method = 'insertAction' )
     * @op( op = 'c' )		
    */
    public function insertAction()
    {
       	if( ! $this->csrfCheck() ){ return false; } 
     
        $data[ 'name' ] = $this->request->getPost( 'name', 'trim' );
        $data[ 'nickname' ] = $this->request->getPost( 'nickname', 'trim' );
        $data[ 'loginname' ] = $this->request->getPost( 'loginname', 'trim' );
        $data[ 'pwd' ] = sha1( md5( $this->request->getPost( 'password', 'trim' ) ) );
        $data[ 'email' ] = $this->request->getPost( 'email', 'email' );
        $data[ 'role_id' ] = $this->request->getPost( 'roleId', 'int' );
        
        $this->validation( $data );
        
        $data[ 'addtime' ] = $data[ 'uptime' ] = TimeUtils::getFullTime();
        $data[ 'delsign' ]  = $data[ 'status' ]  = DBEnums::DELSIGN_NO;
        
        $userName = PriUsers::findFirst( array( 'loginname=?0 and delsign=' . DBEnums::DELSIGN_NO, 'bind' => $data[ 'loginname' ] ) );
        if( $userName )
            return $this->error( '用户名已经存在' );
        
        $user = new PriUsers();
        if( $user->save( $data ) )
            return $this->success( '保存成功' );
        else
            return $this->error( '保存失败'  );
    }
    
    /**
     * 对输入的数据进行验证
     * @param array $data
     */
    private function validation( $data = array() )
    {
        $validation = new Validation();
        $validation->add( 'name', new PresenceOf(array(
            'message' => '姓名必须填写'
        )));
         $validation->add( 'email', new PresenceOf(array(
            'message' => '邮箱必须填写'
        )));
         $validation->add( 'email', new Email(array(
            'message' => '邮箱格式不正确'
        )));
        $messages =  $validation->validate( $data );
        if( count( $messages ))
        {
            foreach( $messages as $msg )
            {
                return $this->error( $msg->getMessage() );
            }
        }
    }
   
}